//
//  MainViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/9.
//

import Foundation
import SwiftUI
import Combine
class MainViewModel : BaseViewModel {
    // 保存定时器，以便管理其生命周期
    private var timer: AnyCancellable?
    // 控制定时器是否活跃的状态
    private var timerIsActive = false
    
    override init() {
        super.init()
        startTimer()
        self.addObserve(self, .background) { (selfInstance, status: Bool) in
            //前后台通知，
            if !status {
                selfInstance.startTimer()
            } else {
                selfInstance.stopTimer()
            }
        }
    }
    func getUpdate() {
        if let appUpdate = configManager.getConfig().appUpdate2 {
            if AppStorageManager.shared.updateVersionStorage != appUpdate.appVersionName ?? "" && appUpdate.isUpdate()  == true {
                AppStorageManager.shared.updateVersionStorage = appUpdate.appVersionName ?? ""
                showVersionTipsDialog(text: appUpdate.content ?? "", btn: "更新") {
                    if let url = URL(string: appUpdate.downloadApk ?? "") {
                        UIApplication.shared.open(url, options: [:], completionHandler: nil)
                    }
                }
            }
        }
    }
    
    
    func requestNetTime() {
        request(isLoading: false) {
            curTime = try await getNetTime()
        }
        suc: {
            
        }
        fail: {_ in }
    }
    
    func startTimer() {
        // 启动一个每60秒触发一次的定时器，并立即自动连接
        // `on: .main` 确保定时器在主线程运行，`in: .common` 表示在通用运行循环模式下运行
        let timerPublisher = Timer.publish(every: 60, on: .main, in: .common).autoconnect()
        
        // 使用sink订阅定时器发出的事件
        timer = timerPublisher.sink { _ in
            showLog("网络网络时间")
            self.requestNetTime()
        }
        timerIsActive = true
        showLog("网络时间开始获取")
        self.requestNetTime()
    }
    
    func stopTimer() {
        // 取消定时器订阅
        timer?.cancel()
        timer = nil
        timerIsActive = false
        showLog("网络时间停止")
    }
    
    
}
